package com.qyhl.webtv.module_news.news.column.detail;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.decoration.RecycleViewDivider;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.news.AdvHomeBean;
import com.qyhl.webtv.commonlib.entity.news.GlobalNewsBean;
import com.qyhl.webtv.commonlib.entity.news.NewsBean;
import com.qyhl.webtv.commonlib.entity.news.NewsStyleBean;
import com.qyhl.webtv.commonlib.item.ItemAdvCommon;
import com.qyhl.webtv.commonlib.item.ItemAdvGroup;
import com.qyhl.webtv.commonlib.item.ItemAdvLarge;
import com.qyhl.webtv.commonlib.item.ItemCatchNews;
import com.qyhl.webtv.commonlib.item.ItemCommonLarge;
import com.qyhl.webtv.commonlib.item.ItemCommonLeft;
import com.qyhl.webtv.commonlib.item.ItemCommonRight;
import com.qyhl.webtv.commonlib.item.ItemCommonThreePics;
import com.qyhl.webtv.commonlib.item.ItemGoodLife;
import com.qyhl.webtv.commonlib.item.ItemNoPicture;
import com.qyhl.webtv.commonlib.item.ItemOtherAdv;
import com.qyhl.webtv.commonlib.item.ItemPicture;
import com.qyhl.webtv.commonlib.item.ItemSmallVideo;
import com.qyhl.webtv.commonlib.item.ItemTitleNews;
import com.qyhl.webtv.commonlib.item.ItemTopNews;
import com.qyhl.webtv.commonlib.item.ItemTopNoPicture;
import com.qyhl.webtv.commonlib.item.ItemUnion;
import com.qyhl.webtv.commonlib.item.ItemVideoLarge;
import com.qyhl.webtv.commonlib.item.ItemVideoLeft;
import com.qyhl.webtv.commonlib.item.ItemVideoRight;
import com.qyhl.webtv.commonlib.utils.ItemSkipUtils;
import com.qyhl.webtv.module_news.news.newslist.NewsListContract;
import com.qyhl.webtv.module_news.news.newslist.NewsListPresenter;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;

@Route(path = ARouterPathConstant.SD_COLUMN_LIST)
public class ColumnNewsDetailActivity extends BaseActivity implements NewsListContract.NewsListView {
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    private String newsId = "0";//新闻最后一条id,用于请求更多数据的参数

    private int page = 1;//请求页数,当sectionId大于100为页数

    private String sectionId; //新闻栏目ID

    private int position;

    private NewsListPresenter mPresenter;

    private int[] pos;//改变样式的位置

    private List<GlobalNewsBean> mDataList = new ArrayList<>();

    private HeaderAndFooterWrapper<GlobalNewsBean> mHeaderAndFooterWrapper;

    private MultiItemTypeAdapter<GlobalNewsBean> mAdapter;

    @Override
    protected int getContentView() {
        return R.layout.news_activity_column_detail;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @SuppressLint("InflateParams")
    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Loading);

        sectionId = getIntent().getStringExtra("id");
        String mTitle = getIntent().getStringExtra("title");
        String logo = getIntent().getStringExtra("cover");

        mPresenter = new NewsListPresenter(this);
        title.setText(mTitle);

        View headView = LayoutInflater.from(this).inflate(R.layout.news_header_column_detail, null);
        ImageView cover = headView.findViewById(R.id.cover);

        Glide.with(this)
                .load(logo)
                .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                .into(cover);

        //设置刷新控件
        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(true);

        //获取样式
        List<NewsStyleBean> styleBeanList = CommonUtils.getInstance().getGlobalStyleBeanList();
        boolean globalStyle = CommonUtils.getInstance().getGlobalStyle();
        if (globalStyle) {
            if (styleBeanList.size() > 0) {
                pos = new int[styleBeanList.size() - 1];
                for (int i = 1; i < styleBeanList.size(); i++) {
                    if (styleBeanList.get(i).getPosition() != 0) {
                        pos[i - 1] = styleBeanList.get(i).getPosition();
                    }
                }
            }
        } else {
            if (styleBeanList != null && styleBeanList.size() > 0) {
                pos = new int[styleBeanList.size()];
                for (int i = 0; i < styleBeanList.size(); i++) {
                    pos[i] = styleBeanList.get(i).getPosition();
                }
            }
        }

        recycleView.setLayoutManager(new LinearLayoutManager(this));
        recycleView.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, 1, ContextCompat.getColor(this, R.color.global_gray_lv4)));
        //初始化适配器
        mAdapter = new MultiItemTypeAdapter<GlobalNewsBean>(this, mDataList);
        mAdapter.addItemViewDelegate(new ItemAdvCommon(this));
        mAdapter.addItemViewDelegate(new ItemAdvGroup(this));
        mAdapter.addItemViewDelegate(new ItemAdvLarge(this));
        mAdapter.addItemViewDelegate(new ItemCatchNews(this));
        mAdapter.addItemViewDelegate(new ItemCommonLarge(this));
        mAdapter.addItemViewDelegate(new ItemCommonRight(this));
        mAdapter.addItemViewDelegate(new ItemCommonLeft(this));
        mAdapter.addItemViewDelegate(new ItemGoodLife(this));
        mAdapter.addItemViewDelegate(new ItemNoPicture(this));
        mAdapter.addItemViewDelegate(new ItemPicture(this));
        mAdapter.addItemViewDelegate(new ItemTitleNews(this));
        mAdapter.addItemViewDelegate(new ItemTopNews(this));
        mAdapter.addItemViewDelegate(new ItemTopNoPicture(this));
        mAdapter.addItemViewDelegate(new ItemVideoLarge(this));
        mAdapter.addItemViewDelegate(new ItemVideoLeft(this));
        mAdapter.addItemViewDelegate(new ItemVideoRight(this));
        mAdapter.addItemViewDelegate(new ItemSmallVideo(this));
        mAdapter.addItemViewDelegate(new ItemUnion(this));
        mAdapter.addItemViewDelegate(new ItemCommonThreePics(this));
        mAdapter.addItemViewDelegate(new ItemOtherAdv(this));

        mHeaderAndFooterWrapper = new HeaderAndFooterWrapper<GlobalNewsBean>(mAdapter);
        mHeaderAndFooterWrapper.addHeaderView(headView);
        recycleView.setAdapter(mHeaderAndFooterWrapper);

        if (Integer.parseInt(sectionId) >= 1000000) {
            mPresenter.getDatas(sectionId, page + "");
        } else {
            mPresenter.getDatas(sectionId, newsId);
        }
    }

    @Override
    protected void setListener() {
        //刷新
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                newsId = "0";
                if (Integer.parseInt(sectionId) >= 1000000) {
                    mPresenter.getDatas(sectionId, page + "");
                } else {
                    mPresenter.getDatas(sectionId, newsId);
                }
            }
        });

        //加载
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (Integer.parseInt(sectionId) >= 1000000) {
                    mPresenter.getDatas(sectionId, page + "");
                } else {
                    mPresenter.getDatas(sectionId, newsId);
                }
            }
        });

        //重新加载
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                page = 1;
                newsId = "0";
                if (Integer.parseInt(sectionId) >= 1000000) {
                    mPresenter.getDatas(sectionId, page + "");
                } else {
                    mPresenter.getDatas(sectionId, newsId);
                }
            }
        });

        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (position != 0) {
                    GlobalNewsBean bean = mDataList.get(position - 1);
                    ItemSkipUtils.getInstance().itemSkip(bean, ColumnNewsDetailActivity.this, view);
                }

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

    }

    @OnClick(R2.id.back_btn)
    public void onViewClicked() {
        finish();
    }

    @Override
    public void setDatas(List<NewsBean> beanList, boolean isMore) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~~");

        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            mDataList.clear();
        }
        setNews(beanList);
    }

    /**
     * 设置新闻
     */
    private void setNews(List<NewsBean> beanList) {
        List<GlobalNewsBean> indexList = new ArrayList<>();
        boolean globalStyle;
        int globalCommon;
        int globalVideo;
        try {
            globalStyle = CommonUtils.getInstance().getGlobalStyle();
            globalCommon = Integer.parseInt(CommonUtils.getInstance().getGlobalCommon());
            globalVideo = Integer.parseInt(CommonUtils.getInstance().getGlobalVideo());
        } catch (Exception e) {
            globalStyle = false;
            globalCommon = 0;
            globalVideo = 0;
        }

        //改变样式
        for (int i = 0; i < beanList.size(); i++) {
            if (isSpecial(i)) {
                if (globalStyle) {
                    position++;
                }
                List<NewsStyleBean> styleBeanList = CommonUtils.getInstance().getGlobalStyleBeanList();
                beanList.get(i).setCommonStyle(styleBeanList.get(position).getCommonStyle());
                beanList.get(i).setVideoStyle(styleBeanList.get(position).getVideoStyle());
            } else {
                beanList.get(i).setCommonStyle(globalCommon);
                beanList.get(i).setVideoStyle(globalVideo);
            }
        }

        if (Integer.parseInt(sectionId) >= 1000000) {
            page++;
        } else {
            try {
                newsId = beanList.get(beanList.size() - 1).getID();
            } catch (Exception e) {
                newsId = "-1";
            }
        }

        //数据类型转换
        for (int i = 0; i < beanList.size(); i++) {
            NewsBean bean = beanList.get(i);
            //是否是无图
            boolean hasPicture = StringUtils.isPictureSuccess(bean.getLogo());
            String type = "", pOne = "", pTwo = "", pThree = "";
            int style = 0;
            switch (bean.getType()) {
                case "1"://普通新闻
                    type = "1";
                    switch (bean.getPluralPicsFlag()) {
                        case 0:
                            style = bean.getCommonStyle();
                            break;
                        case 1://三图
                            hasPicture = false;
                            if (bean.getImagess().size() == 1) {
                                hasPicture = true;
                                pOne = bean.getImagess().get(0).getImageUrlString();
                            } else if (bean.getImagess().size() == 2) {
                                pOne = bean.getImagess().get(0).getImageUrlString();
                                pTwo = bean.getImagess().get(1).getImageUrlString();
                                hasPicture = true;
                            } else if (bean.getImagess().size() >= 3) {
                                pOne = bean.getImagess().get(0).getImageUrlString();
                                pTwo = bean.getImagess().get(1).getImageUrlString();
                                pThree = bean.getImagess().get(2).getImageUrlString();
                                hasPicture = true;
                            } else {
                                hasPicture = false;
                            }
                            style = 4;
                            break;
                        case 2:
                            style = 3;
                            break;
                        default:
                            style = bean.getCommonStyle();
                            break;
                    }
                    break;
                case "2"://图片新闻
                    type = "2";
                    if (bean.getImagess().size() == 1) {
                        pOne = bean.getImagess().get(0).getImageUrlString();
                        hasPicture = true;
                    } else if (bean.getImagess().size() == 2) {
                        pOne = bean.getImagess().get(0).getImageUrlString();
                        pTwo = bean.getImagess().get(1).getImageUrlString();
                        hasPicture = true;
                    } else if (bean.getImagess().size() >= 3) {
                        pOne = bean.getImagess().get(0).getImageUrlString();
                        pTwo = bean.getImagess().get(1).getImageUrlString();
                        pThree = bean.getImagess().get(2).getImageUrlString();
                        hasPicture = true;
                    } else {
                        hasPicture = false;
                    }
                    break;
                case "3"://直播
                    type = "9";
                    break;
                case "4"://标题新闻
                    type = "8";
                    break;
                case "5"://视频新闻
                    type = "3";
                    style = bean.getVideoStyle();
                    break;
                case "8"://互动直播
                    bean.setID(bean.getRoomId());//将roomId设置成通用Id
                    type = "5";
                    break;
                case "101"://抓取新闻
                    type = "10";
                    break;
                default:
                    break;
            }
            indexList.add(new GlobalNewsBean(bean.getTitle(), bean.getID(), bean.getRedirectURL(), bean.getLogo(), style, bean.getPublishDate(), type, Integer.parseInt(bean.getHitCount()), bean.getSource(), bean.getCatalogID(), hasPicture, pOne, pTwo, pThree, bean.getLivetype(), bean.getCommentCount()));
        }
        mDataList.addAll(indexList);
        mHeaderAndFooterWrapper.notifyDataSetChanged();
    }

    /**
     * 判断当前位置是否是特殊位置
     *
     * @return
     */
    private boolean isSpecial(int index) {
        position = 0;
        try {
            for (int i = 0; i < pos.length; i++) {
                if (pos[i] == (index + 1)) {
                    position = i;
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public void setError(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadMask.setErrorText(msg);
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void setEmpty(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadMask.setEmptyText(msg);
        loadMask.setStatus(LoadingLayout.Empty);
        loadMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void setNetError(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadMask.setNoNetworkText(msg);
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void showMessage(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
        loadMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void showLog(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadMask.setReloadButtonText("点击重试~~");
    }

    //---------------------------------------------------------------------------------------------
    @Override
    public void setHeaderNum(int num) {

    }

    @Override
    public void setHeaderError() {

    }

    @Override
    public void setAdvData(List<AdvHomeBean> beanList) {

    }

    @Override
    public void setAdvError(String msg) {

    }

}
